package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;//操作订单表

    @Autowired
    private OrderDetailMapper orderDetailMapper;//操作订单明细表

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional//多表操作事务控制
    public OrderSubmitVO submintOrder(OrdersSubmitDTO ordersSubmitDTO) {
        //1.处理异常情况
        //1.1地址簿为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //检查用户的收获地址是否在配送范围内
        // TODO 注册百度地图的ak未实现
        //checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        //1.2购物车为空
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.list(userId);
        if (shoppingCarts == null || shoppingCarts.isEmpty()) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //2.插入一条订单表数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setOrderTime(LocalDateTime.now());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setPayStatus(Orders.UN_PAID);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setAddress(addressBook.getProvinceName() + "-" + addressBook.getCityName() + "-" +
                addressBook.getDistrictName() + "-" + addressBook.getDetail());
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setUserId(userId);
        orderMapper.insert(orders);
        //3.插入多条订单明细表的数据
        List<OrderDetail> orderDetails = new ArrayList<>();
        //遍历购物车封装订单明细对象
        for (ShoppingCart shoppingCart : shoppingCarts) {
            OrderDetail orderDetail = new OrderDetail();//每次new一个新的订单明细对象
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetails.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetails);
        //4.清空购物车
        shoppingCartMapper.deleteByUserId(userId);
        //5.封装VO返回
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .orderTime(orders.getOrderTime())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .id(orders.getId())
                .build();
        //支付成功通过websocket向管理端发送来单提醒
        Map map = new HashMap<>();
        //参数是type orderid content
        map.put("type",1);//1 表示来单提醒 2 表示客户催单
        map.put("orderId",orders.getId());
        map.put("content","订单号："+orders.getNumber());
        String json = JSON.toJSONString(map);
        //发送信息
        webSocketServer.sendToAllClient(json);
        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
        // TODO 微信的企业认证未实现
        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(outTradeNo);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //支付成功通过websocket向管理端发送来单提醒
        Map map = new HashMap<>();
        //参数是type orderid content
        map.put("type",1);//1 表示来单提醒 2 表示客户催单
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);
        String json = JSON.toJSONString(map);
        //发送信息
        webSocketServer.sendToAllClient(json);
    }

    /**
     * 分页查询用户历史订单
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult pageQuerty(OrdersPageQueryDTO ordersPageQueryDTO) {
        //封装到userid进去
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        //使用pageHelper拼接分页查询条件
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        //正常的条件查询语句但是返回值必须是page select * from 表 where user_id = ? and status = ?
        //查询出订单信息
        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);
        //如果没有历史订单
        if (page == null && page.getTotal() == 0) {
            return new PageResult(0, null);
        }//封装对应订单的所有商品信息 page可以这样使用吗 封装查询的结果result集合
        List<OrderVO> result = page.getResult();
        for (OrderVO orderVo : result) {
            List<OrderDetail> orderDetailList = orderDetailMapper.listByOrderId(orderVo.getId());
            orderVo.setOrderDetailList(orderDetailList);
        }
        PageResult pageResult = new PageResult(page.getTotal(), result);
        return pageResult;
    }

    /**
     * 查询订单和具体的商品
     *
     * @param id
     * @return
     */
    public OrderVO getOrderWithDetail(Long id) {
        //查询订单
        Orders orders = orderMapper.getById(id);
        //查询对应的商品信息
        List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(orders.getId());
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * 取消订单
     *
     * @param id
     */
    public void cancelOrder(Long id) throws Exception {
        Orders orders = orderMapper.getById(id);
        if (orders == null) {//没有找到订单
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //判断订单状态分析不同逻辑
        if (orders.getStatus() > 2) {
            //如果是已接单和派送中不可以直接取消订单 需要电话确认 再取消订单并退款
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }//更新状态 new一个新的对象 不更新的地方设为空
        Orders orders1 = new Orders();//用来修改的对象动态拼接sql
        orders1.setId(id);
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            //如果是待接单 可以直接取消订单 但需要退款 设置付款状态为退款
            weChatPayUtil.refund(orders.getNumber(), orders.getNumber(), new BigDecimal(0.01), new BigDecimal(0.01));
            orders1.setPayStatus(Orders.REFUND);
        }
        //如果是未付款 不需要退款 可以直接取消订单
        //统一执行的方法
        orders1.setStatus(Orders.CANCELLED);
        orders1.setCancelTime(LocalDateTime.now());
        orders1.setCancelReason("用户取消");
        //这样更新是全部更新不好
        orderMapper.update(orders1);
    }

    /**
     * 将上一单的商品再存到购物车中
     *
     * @param id
     */
    public void postShoppingCart(Long id) {
        //根据当前的订单id查询对应的商品
        List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(id);
        //一个商品明细就是一个购物车 转换映射
        Long userId = BaseContext.getCurrentId();
        List<ShoppingCart> shoppingCarts = orderDetails.stream().map((od) -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(od, shoppingCart, "id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        //将商品插入到购物车中
        shoppingCartMapper.insertBatch(shoppingCarts);
    }

    /**
     * 条件查询订单及其商品
     *
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //分页条件查询出订单信息
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);
        if (page == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_IS_NULL);
        }
        //封装成vo对象
        //查询出菜品明细
        List<OrderVO> result = page.getResult();
        for (OrderVO orderVO : result) {
            List<OrderDetail> orderDetails = orderDetailMapper.listByOrderId(orderVO.getId());
            //转化成字符串 封装进去
            String detailsToString = orderDetailsToString(orderDetails);
            orderVO.setOrderDishes(detailsToString);
        }
        return new PageResult(page.getTotal(), result);
    }

    /**
     * 将明细商品集合转化为字符串
     *
     * @param orderDetails
     * @return
     */
    public String orderDetailsToString(List<OrderDetail> orderDetails) {
        //流转化成字符串宫保鸡丁*3的格式
        List<String> strings = orderDetails.stream().map((orderDetail -> {
            //转为字符串
            String detail = orderDetail.getName() + "*" + orderDetail.getNumber();
            return detail;
        })).collect(Collectors.toList());
        //合成一条字符串
        String join = String.join(",", strings);
        return join;
    }

    /**
     * 查询各个订单的状态数量统计
     *
     * @return
     */
    public OrderStatisticsVO statisticsWithStatus() {
        //查询带派送 派送中 待接单
        Integer toBeConfirmed = orderMapper.getStatisticsWithStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.getStatisticsWithStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.getStatisticsWithStatus(Orders.DELIVERY_IN_PROGRESS);
        //封装结果
        OrderStatisticsVO orderStatisticsVO = OrderStatisticsVO.builder()
                .toBeConfirmed(toBeConfirmed)
                .confirmed(confirmed)
                .deliveryInProgress(deliveryInProgress)
                .build();
        return orderStatisticsVO;
    }

    /**
     * 修改订单状态为接单
     *
     * @param ordersConfirmDTO
     */
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        //根据id查询出对应的订单
        Orders orders = orderMapper.getById(ordersConfirmDTO.getId());
        //只有待接单的才可以接单
        if(ordersConfirmDTO.getStatus() != null && !ordersConfirmDTO.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改对应的status属性为3已接单
        Orders o = new Orders();
        o.setId(orders.getId());
        o.setStatus(Orders.CONFIRMED);
        //update修改
        orderMapper.update(o);
    }

    /**
     * 管理端拒单
     *
     * @param ordersRejectionDTO
     */
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        //查询出对应的订单
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
        //如果订单的状态为待接单才可以拒单
        if (orders == null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders o = new Orders();//这是用于修改的空对象
        //如果支付状态为已支付改成退款并且执行退款
        if (orders.getPayStatus().equals(Orders.PAID)) {
            //退款操作
            String refund = weChatPayUtil.refund(orders.getNumber(), orders.getNumber(), new BigDecimal(0.01), new BigDecimal(0.01));
            o.setPayStatus(Orders.REFUND);
        }
        //修改订单的状态为取消 和 修改订单的拒绝原因 取消时间
        o.setId(orders.getId());
        o.setStatus(Orders.CANCELLED);
        o.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        o.setCancelTime(LocalDateTime.now());
        orderMapper.update(o);
    }

    /**
     * 管理端取消订单
     *
     * @param ordersCancelDTO
     */
    public void cancelByAdmin(OrdersCancelDTO ordersCancelDTO) throws Exception {
        //获取订单
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_IS_NULL);
        }
        //用于修改的空对象
        Orders o = new Orders();
        o.setId(orders.getId());
        //如果已支付 退款 设置支付状态为退款
        if (orders.getPayStatus().equals(Orders.PAID)) {
            //退款操作
            String refund = weChatPayUtil.refund(orders.getNumber(), orders.getNumber(), new BigDecimal(0.01), new BigDecimal(0.01));
            o.setPayStatus(Orders.REFUND);
        }
        //更新取消时间 取消原因 订单状态
        o.setCancelTime(LocalDateTime.now());
        o.setCancelReason(ordersCancelDTO.getCancelReason());
        o.setStatus(Orders.CANCELLED);
        orderMapper.update(o);
    }

    /**
     * 派送订单
     *
     * @param id
     */
    public void delivery(Long id) {
        //获取订单
        Orders orders = orderMapper.getById(id);
        //只有已接单的订单才能派送
        if (orders == null || !orders.getStatus().equals(Orders.CONFIRMED)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态为4派送中
        Orders o = new Orders();
        o.setId(orders.getId());
        o.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.update(o);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    public void complete(Long id) {
        //查询出当前的订单
        Orders orders = orderMapper.getById(id);
        //只有派送中的订单可以设置为完成
        if (orders == null || !orders.getStatus().equals(Orders.DELIVERY_IN_PROGRESS)) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        //修改订单状态 5 已完成和完成时间
        Orders o = new Orders();
        o.setId(orders.getId());
        o.setStatus(Orders.COMPLETED);
        o.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(o);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     *
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address", shopAddress);
        map.put("output", "json");
        map.put("ak", ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address", address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin", shopLngLat);
        map.put("destination", userLngLat);
        map.put("steps_info", "0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if (!jsonObject.getString("status").equals("0")) {
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if (distance > 5000) {
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }

    /**
     * 客户催单
     * @param id
     */
    public void remider(Long id) {
        //查询出当前的订单
        Orders orders = orderMapper.getById(id);
        //只有派送中的订单可以设置为完成
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_IS_NULL);
        }
        //订单存在发送催单请求
        Map map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",orders.getId());
        map.put("content","订单号："+orders.getNumber());
        String json = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }
}
